package com.bytech.common.biz.intercept;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.MDC;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.alibaba.fastjson.JSON;
import com.bytech.common.biz.entity.blogUser.BlogUser;
import com.bytech.common.biz.entity.blogUser.BlogUserAgent;
import com.bytech.common.biz.service.remote.user.RemoteBlogUserService;
import com.bytech.common.config.AppGlobalConstants;
import com.bytech.common.utils.JedisClient;
import com.bytech.common.utils.StringUtils;
import com.google.common.collect.Lists;

/**
 * 此拦截器是独立运行在各个微服务上的，主要目的是截获用户请求中携带的token，到redis查询用户信息，若没有则会调用远程用户微服务设置redis缓存并将用户信息设置到session
 *
 * @Author zhao
 * @Create 2021/7/28 15:08
 */
@Component
public class BlogUserAgentIntercept implements HandlerInterceptor, Ordered {

    @Resource
    private JedisClient jedisClient;
    @Resource
    private RemoteBlogUserService remoteBlogUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        BlogUserAgent sessionAgent = (BlogUserAgent) request.getSession().getAttribute(AppGlobalConstants.BLOG_USER_SESSION_KEY);
        if (sessionAgent != null) {
            HttpSession session = request.getSession();
            session.setMaxInactiveInterval(AppGlobalConstants.BLOG_USER_SESSION_EXPIRED); // 10分钟 保持session 10分钟有效 多个节点是分开计时的
        } else {
            Cookie[] cookies = request.getCookies();
            if (!ArrayUtils.isEmpty(cookies)) {
                Optional<Cookie> opCookie = Arrays.stream(cookies).filter(e -> e.getName().equals(AppGlobalConstants.BLOG_USER_COOKIE_KEY)).findFirst();
                if (opCookie.isPresent()) {
                    Cookie cookie = opCookie.get();
                    String accessToken = cookie.getValue();
                    try {
                        String userJson = jedisClient.go(cluster -> cluster.get(AppGlobalConstants.getTokenRedisKey(accessToken)));
                        BlogUser user = null;
                        if (!StringUtils.isBlank(userJson)) {
                            user = JSON.parseObject(userJson, BlogUser.class);
                        } else {
                            user = remoteBlogUserService.getUserByToken(accessToken).getData();
                            if (user != null) {
                                final BlogUser finalUser = user;
                                jedisClient.go(cluster -> cluster.set(AppGlobalConstants.getTokenRedisKey(accessToken), JSON.toJSONString(finalUser)));
                            }
                        }
                        if (user != null) {
                            // cookie 登录
                            HttpSession session = request.getSession();
                            BlogUserAgent userAgent = new BlogUserAgent(user);
                            session.setAttribute(AppGlobalConstants.BLOG_USER_SESSION_KEY, userAgent);
                            session.setMaxInactiveInterval(AppGlobalConstants.BLOG_USER_SESSION_EXPIRED); // 10分钟
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {

                }
            }
        }
        return true;
    }

    @Override
    public int getOrder() {
        return 5;
    }
}